import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiResponseDto } from '../dto/api-response.dto';
import { LoggerService } from '../logger/logger.service';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: LoggerService) {
    this.logger.setContext('HttpException');
  }

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();

    // 记录错误日志
    this.logger.error(
      {
        message: `${request.method} ${request.url} ${status}`,
        path: request.url,
        method: request.method,
        status,
        body: request.body,
        query: request.query,
        ip: request.ip,
        userAgent: request.get('user-agent'),
        error: exception.message,
      },
      exception.stack
    );

    // 构造错误响应
    let errorMessage =
      typeof exceptionResponse === 'string'
        ? exceptionResponse
        : (exceptionResponse as any).message || exception.message;

    // 处理验证错误的详细信息
    if (
      status === HttpStatus.BAD_REQUEST &&
      Array.isArray((exceptionResponse as any)?.message)
    ) {
      errorMessage = (exceptionResponse as any).message.join(', ');
    }

    const errorResponse = ApiResponseDto.error(errorMessage, status);

    response.status(status).json(errorResponse);
  }
}
